package main

import (
	"crypto/md5"
	"encoding/hex"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

var which = flag.Bool("which", true, "")
var path = flag.String("path", "", "")
var cnt = flag.Int("cnt", 10, "")

func method01() string {
	f, err := os.Open(*path)
	checkErr(err)
	defer f.Close()

	body, err := ioutil.ReadAll(f)
	checkErr(err)

	has := md5.Sum(body)
	md5str := fmt.Sprintf("%x", has)
	return md5str
}

func method02() string {
	f, err := os.Open(*path)
	checkErr(err)
	defer f.Close()
	md5hash := md5.New()
	_, err = io.Copy(md5hash, f)
	checkErr(err)
	has := md5hash.Sum(nil)
	md5str := fmt.Sprintf("%x\n", has)
	return md5str
}

//对字符串md5加密
func method03(b []byte) string {
	m5 := md5.New()
	m5.Write(b)
	st := m5.Sum(nil)
	return hex.EncodeToString(st)
}

/**
MD5验证
执行：go run MD5.go -path=E:\BKO.zip -which=false -cnt=10
测试：time ./MD5  -path=E:\BKO.zip -which=false -cnt=10
*/
func main() {
	flag.Parse()
	var md5 string
	for i := 0; i < *cnt; i++ {
		if *which {
			md5 = method01()
		} else {
			md5 = method02()
		}
		fmt.Println(md5)
	}

	md5 = method03([]byte("hahahh"))
	fmt.Println(md5)
}

func checkErr(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error:%s", err.Error())
		os.Exit(1)
	}
}
